package com.example.test_1_21.mqserver.datacenter;

import com.example.test_1_21.common.MQException;
import com.example.test_1_21.mqserver.core.Binding;
import com.example.test_1_21.mqserver.core.Exchange;
import com.example.test_1_21.mqserver.core.MSGQueue;
import com.example.test_1_21.mqserver.core.Message;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

public class DiskDataCenter {
    //管理数据库中的数据
    private DataBaseManager dataBaseManager=new DataBaseManager();
    //管理数据文件中的数据
    private MessageFileManager messageFileManager=new MessageFileManager();

    public void init(){
        //初始化上述两个实例
        dataBaseManager.init();
        messageFileManager.init();
    }

    //封装交换机
    public void insertExchange(Exchange exchange){
        dataBaseManager.insertExchange(exchange);
    }

    public void deleteExchange(String exchangeName){
        dataBaseManager.deleteExchange(exchangeName);
    }

    public List<Exchange> selectAllExchanges(){
        return dataBaseManager.selectAllExchanges();
    }

    //封装队列
    public void insertQueue(MSGQueue queue) throws IOException {
        dataBaseManager.insertQueue(queue);
        //创建队列的同时，不仅仅是把对象写到数据库中，还需要创建对应的目录和文件
        messageFileManager.createQueueFiles(queue.getName());
    }

    public void deleteQueue(String queueName) throws IOException {
        dataBaseManager.deleteQueue(queueName);
        //删除队列的同时，不仅仅把队列从数据库中删除，还需要删除对应的目录文件
        messageFileManager.destroyQueueFiles(queueName);
    }

    public List<MSGQueue> selectAllQueues(){
        return dataBaseManager.selectAllQueues();
    }

    //封装绑定
    public void insertBinding(Binding binding){
        dataBaseManager.insertBinding(binding);
    }

    public void deleteBinding(Binding binding){
        dataBaseManager.deleteBinding(binding);
    }

    public List<Binding> selectAllBindings(){
        return dataBaseManager.selectAllBindings();
    }

    //封装消息操作
    public void sendMessage(MSGQueue queue, Message message) throws MQException, IOException {
        messageFileManager.sendMessage(queue,message);
    }

    public void deleteMessage(MSGQueue queue,Message message) throws IOException, ClassNotFoundException, MQException {
        messageFileManager.deleteMessage(queue,message);
        if(messageFileManager.checkGC(queue.getName())){
            messageFileManager.gc(queue);
        }
    }

    public LinkedList<Message> loadAllMessageFromQueue(String queueName) throws MQException, IOException, ClassNotFoundException {
        return messageFileManager.loadAllMessageFromQueue(queueName);
    }
}
